<!--
 * @Author: fyukeeh 15849141465@163.com
 * @Date: 2025-07-23 19:58:47
 * @LastEditors: fyukeeh 15849141465@163.com
 * @LastEditTime: 2025-07-23 20:18:30
 * @FilePath: \mapbox\src\views\example\TiandituBasemap.vue
 * @Description: 天地图底图切换示例，全部通过controller+basemaps自动集成
-->
<template>
  <div class="map-page">
    <div id="map" class="map-container"></div>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import Map from '289-map'

const TDT_KEY = '598b1d1a4ed6d42ce765e7b6c3737c6b'
const basemaps = [
  {
    id: 'tdt-vector',
    label: '天地图矢量',
    thumb: 'https://api.tianditu.gov.cn/img/vec.png',
  },
  {
    id: 'tdt-image',
    label: '天地图影像',
    thumb: 'https://api.tianditu.gov.cn/img/img.png',
  },
  {
    id: 'tdt-terrain',
    label: '天地图地形',
    thumb: 'https://api.tianditu.gov.cn/img/ter.png',
  },
]
let map

function addTdtSourceAndLayer(map, item, visible) {
  const tiles = [`https://t0.tianditu.gov.cn/DataServer?T=${item.id === 'tdt-vector' ? 'vec_w' : item.id === 'tdt-image' ? 'img_w' : 'ter_w'}&x={x}&y={y}&l={z}&tk=${TDT_KEY}`]
  if (!map.getSource(item.id)) {
    map.addSource(item.id, {
      type: 'raster',
      tiles,
      tileSize: 256,
      attribution: '© 天地图'
    })
  }
  if (!map.getLayer(item.id + '-layer')) {
    map.addLayer({
      id: item.id + '-layer',
      type: 'raster',
      source: item.id,
      layout: { visibility: visible ? 'visible' : 'none' }
    }, map.getStyle().layers?.[0]?.id)
  }
}

onMounted(() => {
  map = new Map('map', {
    style: {
      version: 8,
      sources: {},
      layers: [],
    },
    center: [116.40, 39.90],
    zoom: 5,
    controller: ["showZoom", "showCompass", "fullscreen", "basemapSwitcher"],
    basemaps,
    attributionControl: true,
  })
  map.on('load', () => {
    basemaps.forEach((item, idx) => {
      addTdtSourceAndLayer(map, item, idx === 0)
    })
  })
})
</script>

<style scoped>
.map-page {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}
.map-container {
  width: 100%;
  height: 100%;
}
</style> 